package org.anachronos.jeep.ui.trace;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.anachronos.jeep.core.attach.VirtualMachineAttachement;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

public class TakeSnapShotCommand extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		try {
			final IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
			final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("profiler");
			if (!project.exists()) {
				project.create(null);
			}
			project.open(null);
			final IFile file = project.getFile(new Path(getTraceFileName()));
			final String fullFilePath = file.getLocation().toOSString();
			final IStructuredSelection currentSelection = 
				(IStructuredSelection) HandlerUtil.getCurrentSelectionChecked(event);
			final VirtualMachineAttachement vm = 
				(VirtualMachineAttachement) currentSelection.iterator().next();
			vm.getProfilerRemoteControl().stopProfiling();
			vm.getProfilerRemoteControl().save(fullFilePath);
			file.refreshLocal(1, null);
			URIEditorInput editorInput = new URIEditorInput(URI.createFileURI(fullFilePath));
			workbenchWindow.getActivePage()
			.openEditor(editorInput, "org.anachronos.jeep.ui.editor.trace");
		} catch (final Exception e) {
			throw new ExecutionException("", e);
		}
		return null;
	}
	
	private String getTraceFileName() {
		final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		final Date date = new Date();
		return format.format(date).concat(".trace");
	}
}
